package com.halflife.comeElectricity.member.merchant;

import com.halflife.comeElectricity.admin.DateUtil;
import com.halflife.comeElectricity.member.rider.PayLog;
import com.halflife.comeElectricity.member.rider.PayLogRepository;
import com.halflife.comeElectricity.member.rider.Rider;
import com.halflife.comeElectricity.member.rider.RiderRepository;
import com.halflife.comeElectricity.orderMng.history.HistoryOrder;
import com.halflife.comeElectricity.orderMng.history.HistoryOrderRepository;
import com.halflife.comeElectricity.orderMng.order.OrderEnum;
import com.halflife.comeElectricity.orderMng.order.OrderRiderController;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;

@Controller
@RequestMapping("/admin")
public class MerchantAdminController {

    private Logger log = LoggerFactory.getLogger(OrderRiderController.class);
    @Resource
    private MerchantRepository merchantRepository;
    @Resource
    private RiderRepository riderRepository;
    @Resource
    private HistoryOrderRepository historyOrderRepository;
    @Resource
    private PayLogRepository payLogRepository;

    /**
     * 商户管理 edit by liuj3
     * @param response
     * @param request
     * @param
     * @return
     */
    @RequestMapping("/admin_merchant/list")
    public String merchant(String merchantName, Integer pageNo, Integer pageSize, HttpServletResponse response,
                           HttpServletRequest request, Model model) {

        //推送分页Map参数
        if(pageNo==null)
            pageNo= 1;
        if(pageSize==null)
            pageSize= 20;
        HashMap<String, Object> param = new HashMap();
        if(merchantName!=null && merchantName!="")
            param.put("merchantName", merchantName);
        param.put("currentPage", (pageNo-1)*pageSize);
        param.put("pageSize", pageSize);
        // param.put("merchantId", merchant.getId());
        int totalCount = merchantRepository.selectMerchantCountOrderByPage(param);
        //查询列表
        List<Merchant> list = merchantRepository.selectMerchantByPage(param);
        //计算总页数
        int totalPage = totalCount/pageSize;
        if(totalCount%pageSize!= 0)
            totalPage++;
        model.addAttribute("list",list);
        model.addAttribute("merchantName",merchantName);
        model.addAttribute("totalPage",totalPage);
        model.addAttribute("pageNo",pageNo);
        model.addAttribute("pageSize",pageSize);
        model.addAttribute("totalCount",totalCount);
        return "merchant/list";
    }

    /**
     * 骑手管理 edit by liuj3
     * @param response
     * @param request
     * @param
     * @return
     */
    @RequestMapping("/admin_merchant/rider/list")
    public String rider(String riderName, String phone, Integer pageNo, Integer pageSize, HttpServletResponse response,
                        HttpServletRequest request, Model model) {

        //推送分页Map参数
        if(pageNo==null)
            pageNo= 1;
        if(pageSize==null)
            pageSize= 20;
        HashMap<String, Object> param = new HashMap();
        if(riderName!=null && riderName!="")
            param.put("riderName", riderName);
        if(StringUtils.isNotBlank(phone)){
            param.put("phone", phone);
        }
        param.put("currentPage", (pageNo-1)*pageSize);
        param.put("pageSize", pageSize);
        // param.put("merchantId", merchant.getId());
        int totalCount = riderRepository.selectCount(param);
        //查询列表
        List<Rider> list = riderRepository.selectListByPage(param);
        //计算总页数
        int totalPage = totalCount/pageSize;
        if(totalCount%pageSize!= 0)
            totalPage++;
        model.addAttribute("list",list);
        model.addAttribute("riderName",riderName);
        model.addAttribute("totalPage",totalPage);
        model.addAttribute("pageNo",pageNo);
        model.addAttribute("pageSize",pageSize);
        model.addAttribute("totalCount",totalCount);
        return "merchant/rider/list";
    }

    /**
     * 骑手领钱管理
     * @param merchartName
     * @param
     * @param dateRangeBe
     * @param dateRangeEn
     * @param pageNo
     * @param pageSize
     * @param request
     * @param response
     * @param model
     * @return
     */
    @RequestMapping("/admin_merchant/riderAccount/list")
    public String gotoRiderAccountList(Integer status, String merchartName, Integer riderId,
                                       String dateRangeBe, String dateRangeEn, Integer pageNo,
                                       Integer pageSize, HttpServletRequest request,
                                       HttpServletResponse response, Model model) {
        //Merchant merchant  =  ShiroUtil.getMerchant();
        BigDecimal riderAccount;
        //推送分页Map参数
        if(pageNo==null)
            pageNo= 1;
        if(pageSize==null)
            pageSize= 20;
        HashMap<String, Object> param = new HashMap();
        if(status!=null)
            param.put("status", status);
        if(dateRangeBe!=null && dateRangeBe!="")
            param.put("dateRangeBe", DateUtil.transForMilliSecondByTim(dateRangeBe));
        if(dateRangeEn!=null && dateRangeEn!="")
            param.put("dateRangeEn",DateUtil.transForMilliSecondByTim(dateRangeEn));
        if(merchartName!=null && merchartName!="")
            param.put("merchartName", merchartName);
        if(riderId!=null)
            param.put("riderId", riderId);
        //计算总额
        HashMap<String, Object> param_ = new HashMap();
        param_.put("riderId", riderId);
        param_.put("status", status);
        if(status== OrderEnum.PAYED.m_orderStatus){
            param_.put("currentPage", (pageNo-1)*pageSize);
            param_.put("pageSize", pageSize);
        }
        if(status== OrderEnum.FINISHED.m_orderStatus || status== OrderEnum.PAYED.m_orderStatus){

            riderAccount = historyOrderRepository.selectRiderAccountOrderByPage(param_);
            model.addAttribute("riderAccount",riderAccount);
        }
        if(status== OrderEnum.PAYED.m_orderStatus) {

            param.put("currentPage", (pageNo - 1) * pageSize);
            param.put("pageSize", pageSize);
           // param.put("merchantId", merchant.getId());
        }
        int totalCount = historyOrderRepository.selectHistoryCountOrderByPage(param);
        //查询列表
        List<HistoryOrder> list = historyOrderRepository.selectHistoryOrderByPage(param);
        //计算总页数
        int totalPage = 0;
        if(status== OrderEnum.PAYED.m_orderStatus) {

            totalPage = totalCount / pageSize;
            if (totalCount % pageSize != 0)
                totalPage++;
        }
        model.addAttribute("dateRangeBe",dateRangeBe);
        model.addAttribute("dateRangeEn",dateRangeEn);
        model.addAttribute("merchartName",merchartName);
        model.addAttribute("riderId",riderId);
        model.addAttribute("list",list);
        model.addAttribute("status",status);
        if(status== OrderEnum.PAYED.m_orderStatus) {

            model.addAttribute("totalPage",totalPage);
            model.addAttribute("pageNo",pageNo);
            model.addAttribute("pageSize",pageSize);
            model.addAttribute("totalCount",totalCount);
        }
        return "merchant/rider/accountlist";
    }


    @RequestMapping("/admin_merchant/rider_orderAccount/account")
    public ResponseEntity getAccountbyIds(String ids, HttpServletRequest request,
                                          HttpServletResponse response, Model model) {
        try{

            BigDecimal totalCount;
            HashMap<String, Object> param = new HashMap();
            List<String> list = new ArrayList<String>();
            if(ids!=null&&ids!=""){

                String[] l = ids.split(",");
                for(String i : l){
                    if(i!=null&i!="")
                        list.add(i);
                }
                param.put("ids",list);
                totalCount = historyOrderRepository.selectOrderAccountSumByIds(param);
                return new ResponseEntity(totalCount, HttpStatus.OK);
            }else
                return new ResponseEntity(1, HttpStatus.EXPECTATION_FAILED);
        } catch (Exception e) {

            log.error(e.getMessage(), e);
            return new ResponseEntity(1, HttpStatus.EXPECTATION_FAILED);
        }
    }

    @RequestMapping("/admin_merchant/rider/setState")
    public ResponseEntity setRiderState(Integer id, Integer state) {
        try {
            Rider rider = new Rider();
            rider.setId(id);
            rider.setState(state);
            riderRepository.updateByPrimaryKeySelective(rider);
        } catch (Exception ex) {
            log.error(ex.toString(),ex);
            return new ResponseEntity(1, HttpStatus.INTERNAL_SERVER_ERROR);
        }
        return new ResponseEntity(0, HttpStatus.OK);
    }

    @RequestMapping("/admin_merchant/rider_orderAccount/update")
    public ResponseEntity updateAccountbyIds(String ids, String memo, String riderId, HttpServletRequest request,
                                             HttpServletResponse response, Model model) {
        try{

            BigDecimal totalCount;
            HashMap<String, Object> param = new HashMap();
            List<String> list = new ArrayList<String>();
            if(ids!=null&&ids!=""){

                String[] l = ids.split(",");
                for(String i : l){
                    if(i!=null&i!="")
                        list.add(i);
                }
                param.put("ids",list);
                totalCount = historyOrderRepository.selectOrderAccountSumByIds(param);
                //更新订单状态
                param.put("status",OrderEnum.PAYED.m_orderStatus);
                historyOrderRepository.updateOrderStatus(param);
                //生成付款记录
                PayLog log = new PayLog();
                log.setRiderId(Integer.parseInt(riderId));
                log.setPayMoney(totalCount);
                log.setMemo(memo);
                log.setCreateDate(Calendar.getInstance().getTimeInMillis());
                payLogRepository.insert(log);
                return new ResponseEntity(1, HttpStatus.OK);
            }else
                return new ResponseEntity(1, HttpStatus.EXPECTATION_FAILED);
        } catch (Exception e) {

            log.error(e.getMessage(), e);
            return new ResponseEntity(1, HttpStatus.EXPECTATION_FAILED);
        }
    }
}
